<?php
namespace api\modules\h5\controllers\order;

use backend\widgets\provinces\Provinces;
use common\components\Pay;
use common\models\cart\Cart;
use common\models\goods\Goods;
use common\models\member\MemberAuth;
use wechat\models\OrderForm;
use yii\data\ActiveDataProvider;
use Yii;
use yii\web\NotFoundHttpException;
use api\controllers\OnAuthController;
use common\enums\StatusEnum;
use common\helpers\ResultDataHelper;
use common\models\store\Store;

/**
 * 订单接口
 *
 * Class InfoController
 * @package api\modules\h5\controllers\order
 * @property \yii\db\ActiveRecord $modelClass
 * @author tjj
 */
class InfoController extends OnAuthController
{
    public $modelClass = 'common\models\order\Order';

    /**
     * 创建订单
     * @return mixed|\yii\db\ActiveRecord
     */
    public function actionCreateOrder()
    {
        $request = Yii::$app->request;
        $store_id = $request->post('store_id')??0;
        $cart_id = $request->post('cart_id')??'';
        $cart_id = explode('|',$cart_id);
        $address_id  = $request->post('address_id')??0;

        if(!$store_id)
            return ResultDataHelper::api(422, '店铺ID不能为空');

        if(empty($cart_id))
            return ResultDataHelper::api(422, '购物车ID不能为空');

        if(!$address_id)
            return ResultDataHelper::api(422, '地址ID不能为空');

        $member_id = Yii::$app->user->identity->member_id;
        $member_auth = MemberAuth::findOne(['member_id'=>$member_id,'oauth_client'=>'wechat']);

        if(!$member_auth)
            return ResultDataHelper::api(422, '用户微信未授权');

        $openid = $member_auth->oauth_client_user_id;

        //生成订单
        $model = new OrderForm();
        $model->attributes = [
            'store_id' => $store_id,
            'payment_code'=>'Wechat',
            'cart_id'=>json_encode($cart_id),
            'member_id' => $member_id,
            'openid'=>$openid,
            'store_name' => '',
            'buyer_name' => '',
            'address_id'=>$address_id
        ];

        if ($model->validate())
        {
            $res = $model->addH5();

            if($res['status'] == 1){
                return $res['data'];
            }else
                return ResultDataHelper::api(422, $res['message']);
        }
    }

    /**
     * 订单列表
     * @return ActiveDataProvider
     */
    public function actionIndex()
    {
        $request = Yii::$app->request;
        $status = $request->get('status')??null;
        $member_id = Yii::$app->user->identity->member_id;

        $query = $this->modelClass::find()
            ->select(['order_id','order_sn','pay_sn','buyer_id','address_id','created_at','payment_code','payment_time','finnshed_time','goods_amount','order_amount','evaluation_state','order_state','refund_state','shipping_code'])
            ->with(['buyer','goods','address'])
            ->where(['buyer_id'=>$member_id])
            ->asArray();

        if(!is_null($status) && !empty($status))
            $query->andWhere(['order_state'=>$status]);

        return new ActiveDataProvider([
            'query' => $query,
            'pagination' => [
                'pageSize' => Yii::$app->params['user.pageSize'],
                'validatePage' => false,// 超出分页不返回data
            ],
        ]);
    }

    /**
     * 详情
     * @param $id
     * @return \yii\db\ActiveRecord
     * @throws NotFoundHttpException
     */
    public function actionView($id)
    {
        $member_id = Yii::$app->user->identity->member_id;

        $data = $this->modelClass::find()
            ->select(['order_id','order_sn','pay_sn','buyer_id','address_id','created_at','payment_code','payment_time','finnshed_time','goods_amount','order_amount','evaluation_state','order_state','refund_state','shipping_code'])
            ->with(['buyer','goods','address'])
            ->where(['buyer_id'=>$member_id])
            ->andWhere(['order_id'=>$id])
            ->asArray()
            ->one();

        return $data;
    }


    public function actionUpdate($id)
    {
        return parent::actionUpdate($id); // TODO: Change the autogenerated stub
    }

    public function actionCreate()
    {
        return parent::actionCreate(); // TODO: Change the autogenerated stub
    }

    /**
     * 权限验证
     *
     * @param string $action 当前的方法
     * @param null $model 当前的模型类
     * @param array $params $_GET变量
     * @throws \yii\web\BadRequestHttpException
     */
    public function checkAccess($action, $model = null, $params = [])
    {
        // 方法名称
        if (in_array($action, ['create','update','delete']))
        {
            throw new \yii\web\BadRequestHttpException('权限不足');
        }
    }
}
